package net.color4me.app.farmere.server;

import java.net.URL;
import java.util.List;
import java.util.Map;

import net.color4me.app.farmere.Constant;
import net.color4me.app.farmere.utils.CookieStrUtil;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class SimpleHttpClient {
	private final StringBuffer cookiesb;
	public URLFetchService urlFetchService;

	/*
	 * 
	 * 没有cookie 传入""
	 */
	public SimpleHttpClient(String cookie) {
		urlFetchService = URLFetchServiceFactory.getURLFetchService();
		cookiesb = new StringBuffer();
		cookiesb.append(cookie);
	}

	public String fetch(String urlstr) throws Exception {
		URL url = new URL(urlstr);
		HTTPRequest req = new HTTPRequest(url, HTTPMethod.GET);

		if (!cookiesb.toString().equals(""))
			req.addHeader(new HTTPHeader("Cookie", cookiesb.toString()));
		HTTPResponse res = urlFetchService.fetch(req);
		if (res.getResponseCode() == 200) {
			processSetCookie(res.getHeaders());
			return getContent(res);
		}
		return null;

	}

	public String post(String urlstr) throws Exception {
		URL url = new URL(urlstr);
		HTTPRequest req = new HTTPRequest(url, HTTPMethod.POST);
		req.addHeader(new HTTPHeader("User-Agent", Constant.USER_AGENT));
		HTTPResponse res = urlFetchService.fetch(req);
		if (res.getResponseCode() == 200) {
			processSetCookie(res.getHeaders());
			return getContent(res);
		}
		return null;
	
	}

	private void processSetCookie(List<HTTPHeader> headers) {
		for (HTTPHeader h : headers) {
			if (h.getName().equals("Set-Cookie")) {
				String setcookiestr = h.getValue();
				Map<String, String> maps = CookieStrUtil.process(setcookiestr);
				for (String s : maps.keySet()) {
					cookiesb.append("; " + s + "=" + maps.get(s));
				}
				if (cookiesb.indexOf("; ") == 0) {
					cookiesb.delete(0, 2);
				}
			}
		}

	}

	private String getContent(HTTPResponse res) throws Exception {
		byte[] bytes = res.getContent();
		return new String(bytes, "UTF-8");
	}

	public String getCookiestr() {
		return cookiesb.toString();
	}

	public void addCookiestr(String cookiestr) {
		this.cookiesb.append("; " + cookiestr);
		if (cookiesb.indexOf("; ") == 0) {
			cookiesb.delete(0, 2);
		}
	}
}
